﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ATPlatforms.RabbitSkin.Serializers
{
    public class XMLMessageSerializer<T> : ISerializeMessages<T>
    {
        private XmlSerializer xs = new XmlSerializer(typeof(T));

        public byte[] SerializeMessage(T message)
        {
            MemoryStream memoryStream = new MemoryStream();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            xs.Serialize(xmlTextWriter, message);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            return memoryStream.ToArray();
        }

        public T DeSerializeMessage(byte[] message)
        {
            MemoryStream memoryStream = new MemoryStream(message);
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            return (T) xs.Deserialize(memoryStream);
        }
    }
}
